package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * app端登录功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //首先判断是正常登陆还是游客登陆
        if(!StringUtils.isEmpty(dto.getPhone())&&!StringUtils.isEmpty(dto.getPassword()))
        {
            //1,正常登陆
            //判断用户名是否存在
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
           if(user==null)
               throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            //判断密码是否正确
            String encode = MD5Utils.encode(dto.getPassword() + user.getSalt());
            if(!encode.equals(user.getPassword()))
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            //判断状态是否禁用
            if(user.getStatus())
            {
                throw new CustomException(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
            }
            //将用户的信息提取出来，并且用id生成token，存入map集合中
            String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
            HashMap<String, Object> claim = new HashMap<>();
            claim.put("token",token);
            //将用户的敏感信息清空再将User存放进入map中去
            user.setPassword("");
            user.setSalt("");
            claim.put("user",user);
            return ResponseResult.okResult(claim);
        }
        //2,游客登陆
        else {
            //将用户的id设置为0并且生成token，存入map集合中
            String token = AppJwtUtil.getToken(0L);
            HashMap<String,Object> claim=new HashMap<>();
            claim.put("token",token);
            //返回的map集合
            return ResponseResult.okResult(claim);
        }
    }
}
